package com.coursehub.shared.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 共享配置类
 */
@Configuration
public class SharedConfig {
    
    /**
     * RestTemplate配置
     */
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        RestTemplate restTemplate = builder
                .setConnectTimeout(Duration.ofSeconds(10))
                .setReadTimeout(Duration.ofSeconds(30))
                .build();
        
        // 添加请求拦截器，传递认证头信息
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add((request, body, execution) -> {
            // 获取当前请求的认证信息
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest httpRequest = attributes.getRequest();
                
                // 传递Authorization头 - 优先从请求属性获取，然后从请求头获取
                String authHeader = (String) httpRequest.getAttribute("Authorization");
                System.out.println("[DEBUG] RestTemplate Interceptor - Authorization from attribute: " + authHeader);
                if (authHeader == null) {
                    authHeader = httpRequest.getHeader("Authorization");
                    System.out.println("[DEBUG] RestTemplate Interceptor - Authorization from header: " + authHeader);
                }
                if (authHeader != null) {
                    request.getHeaders().set("Authorization", authHeader);
                    System.out.println("[DEBUG] RestTemplate Interceptor - Setting Authorization header: " + authHeader);
                } else {
                    System.out.println("[DEBUG] RestTemplate Interceptor - No Authorization header found!");
                }
                
                // 传递用户信息头 - 优先从请求属性获取，然后从请求头获取
                String userId = (String) httpRequest.getAttribute("X-User-Id");
                if (userId == null) {
                    userId = httpRequest.getHeader("X-User-Id");
                }
                if (userId != null) {
                    request.getHeaders().set("X-User-Id", userId);
                }
                
                String userAccount = (String) httpRequest.getAttribute("X-User-Account");
                if (userAccount == null) {
                    userAccount = httpRequest.getHeader("X-User-Account");
                }
                if (userAccount != null) {
                    request.getHeaders().set("X-User-Account", userAccount);
                }
                
                // 同时传递用户名头信息（如果存在）
                String userName = (String) httpRequest.getAttribute("X-User-Name");
                if (userName == null) {
                    userName = httpRequest.getHeader("X-User-Name");
                }
                if (userName != null) {
                    request.getHeaders().set("X-User-Name", userName);
                }
            }
            
            return execution.execute(request, body);
        });
        
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
    
    /**
     * ObjectMapper配置
     */
    @Bean
    public ObjectMapper objectMapper() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        javaTimeModule.addSerializer(new LocalDateTimeSerializer(formatter));
        javaTimeModule.addDeserializer(java.time.LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        
        return Jackson2ObjectMapperBuilder.json()
                .modules(javaTimeModule)
                .propertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE)
                .build();
    }
}